<template>
  <div class="app-container">
    <el-card class="query-card">
      <el-form ref="query" :model="page.query" inline label-position="right" label-width="80px">
        <el-form-item label="订单日期" prop="orderDateRange">
          <el-date-picker
            v-model="page.query.orderDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="page.query.orderNo" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerId">
          <customer-query ref="customerQuery" v-model="page.query.customerId" @choose="handleChooseCustomer" />
        </el-form-item>
        <el-form-item label="付款状态" prop="paymentState">
          <dict-select
            ref="dictSelect1"
            v-model="page.query.paymentState"
            type="button"
            dict-key="payment_state"
            placeholder="请选择付款状态"
            @input="handleDictSelectChange"
          />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <dict-select
            ref="dictSelect2"
            v-model="page.query.priority"
            type="button"
            dict-key="priority"
            placeholder="请选择优先级"
            @input="handleDictSelectChange"
          />
        </el-form-item>
        <el-form-item label="发货状态" prop="shipmentState">
          <dict-select
            ref="dictSelect3"
            v-model="page.query.shipmentState"
            type="button"
            dict-key="shipment_state"
            placeholder="请选择发货状态"
            @input="handleDictSelectChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetQueryForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="table-card">
      <el-tabs v-model="page.query.orderState" @tab-click="handleTabClick">
        <el-tab-pane
          v-for="(item,index) in orderStateList"
          :key="index"
          :label="item.stateName+'('+item.count+')'"
          :name="item.state"
        />
      </el-tabs>
      <!--      <div>
        <span>销售订单列表</span>
      </div>
      <el-divider />-->
      <div class="table-button">
        <el-button
          type="primary"
          :loading="tableLoading"
          class="el-icon-plus"
          @click="saveClick"
        >新增订单
        </el-button>
        <el-button
          type="warning"
          plain
          :loading="tableLoading"
          class="el-icon-edit"
          @click="updateClick('tableBtn')"
        >修改订单
        </el-button>
        <el-button
          type="info"
          plain
          :loading="tableLoading"
          class="el-icon-warning"
          @click="cancelClick('tableBtn')"
        >取消订单
        </el-button>
        <el-button
          plain
          type="success"
          class="el-icon-document-copy"
          :loading="tableLoading"
          @click="produceClick"
        >安排生产</el-button>
        <el-button
          plain
          type="primary"
          class="el-icon-document-copy"
          :loading="tableLoading"
          @click="osClick"
        >订单外发</el-button>
        <el-button
          type="danger"
          :loading="tableLoading"
          plain
          class="el-icon-folder-delete"
          @click="handleBatchDelete"
        >批量删除</el-button>
        <el-button
          type="primary"
          plain
          :loading="tableLoading"
          class="el-icon-data-analysis"
          @click="bomClick"
        >利润计算
        </el-button>
        <el-button
          type="danger"
          plain
          :loading="tableLoading"
          class="el-icon-switch-button"
          @click="terminationClick"
        >提前终止
        </el-button>
        <download-button :disabled="tableData.length===0" :params="page.query" :path="downloadApiPath" icon="el-icon-download" plain />
        <el-tooltip content="刷新" class="table-right-btn">
          <el-button size="mini" circle icon="el-icon-refresh" @click="doPage" />
        </el-tooltip>
      </div>
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="45" />
        <el-table-column width="45">
          <template slot-scope="scope">
            <div v-if="scope.row.orderState==='4'">
              <i class="el-icon-error" />
            </div>
            <div v-else-if="scope.row.orderState==='3'">
              <svg-icon icon-class="finished" style="font-size: 17px;width:20px;display: inline;" />
            </div>
            <div v-else>
              <svg-icon v-if="scope.row.priority==='1'" icon-class="jiaji" style="font-size: 20px;width:20px;display: inline;" />
              <svg-icon v-if="scope.row.priority==='0'" icon-class="putong" style="font-size: 17px;width:20px;display: inline;" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="订单编号" prop="orderNo" min-width="110">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="infoClick(scope.row)"
            >{{ scope.row.orderNo }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="订单日期" prop="orderDate" min-width="100" />
        <el-table-column label="客户名称" prop="customerName" min-width="120" />
        <el-table-column label="产品名称" prop="productName" min-width="200" />
        <el-table-column label="单价" prop="unitPrice" min-width="80">
          <template slot-scope="scope">
            <money-format v-model="scope.row.unitPrice" />
          </template>
        </el-table-column>
        <el-table-column label="数量" prop="quantity" min-width="90">
          <template slot-scope="scope">
            {{ scope.row.quantity }}{{ scope.row.unit }}
          </template>
        </el-table-column>
        <el-table-column label="含税总额" prop="amount" min-width="110">
          <template slot-scope="scope">
            <money-format v-model="scope.row.amount" />
          </template>
        </el-table-column>
        <el-table-column label="不含税总额" prop="unTaxAmount" min-width="120">
          <template slot-scope="scope">
            <money-format v-model="scope.row.unTaxAmount" />
          </template>
        </el-table-column>
        <el-table-column label="订单状态" prop="orderState" min-width="90">
          <template slot-scope="scope">
            <sale-order-state-tag v-model="scope.row.orderState" />
          </template>
        </el-table-column>
        <el-table-column label="付款状态" prop="paymentState" min-width="100">
          <template slot-scope="scope">
            <payment-state-tag v-model="scope.row.paymentState" />
          </template>
        </el-table-column>
        <el-table-column label="付款金额" prop="paidAmount" min-width="100">
          <template slot-scope="scope">
            <money-format v-model="scope.row.paidAmount" />
          </template>
        </el-table-column>
        <el-table-column label="发货状态" prop="shipmentState" min-width="100">
          <template slot-scope="scope">
            <shipment-state-tag v-model="scope.row.shipmentState" />
          </template>
        </el-table-column>
        <el-table-column label="发货数量" prop="shippedQuantity" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.shippedQuantity }}{{ scope.row.unit }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="60" fixed="right">
          <template slot-scope="scope">
            <el-button
              type="text"
              :disabled="scope.row.orderState!=='0'&&scope.row.orderState!=='1'"
              @click="updateClick('column',scope.row)"
            >修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :page-sizes="[10, 20, 30, 40]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <div v-if="bomVisible">
      <bom-detail-module ref="bomModule" :visible="bomVisible" @close="handleCloseBom" />
    </div>
    <div v-if="updateVisible">
      <update-module ref="updateModule" :visible="updateVisible" @close="handleCloseUpdate" />
    </div>
    <div v-if="osVisible">
      <os-order-module ref="osOrderModule" :visible="osVisible" @close="handleCloseOs" />
    </div>
  </div>
</template>

<script>
import {
  order_delete,
  order_page,
  order_cancel,
  order_state_count,
  order_termination
} from '@/api/sale/order'
import { produce } from '@/api/erp/produce'
import BomDetailModule from '@/views/sale/order/modules/bomDetailModule.vue'
import updateModule from '@/views/sale/order/modules/updateModule.vue'
import osOrderModule from '@/views/sale/osOrder/modules/submitModule.vue'

export default {
  name: 'Index',
  components: { osOrderModule, updateModule, BomDetailModule },
  data() {
    return {
      tableData: [],
      tableLoading: false,
      selected: [],
      downloadApiPath: '/api/sale/order/export',
      bomVisible: false,
      updateVisible: false,
      osVisible: false,
      orderStateList: [],
      page: {
        page: 1,
        size: 10,
        total: 0,
        query: {
          fileName: '订单信息',
          orderNo: '',
          orderDateRange: [],
          customerId: '',
          orderState: '0',
          paymentState: '-1',
          priority: '-1',
          shipmentState: '-1'
        }
      }
    }
  },
  mounted() {
    this.doPage()
  },
  methods: {
    handleSearch() {
      this.page.page = 1
      this.doPage()
    },
    doPage() {
      // 分页查询
      this.tableLoading = true
      order_page(this.page).then(resp => {
        if (resp.success) {
          this.tableData = resp.data.records
          this.page.total = resp.data.total
          this.tableData.forEach(e => {
            e.isEdit = false
          })
        }
      }).finally(() => {
        this.tableLoading = false
      })
      this.selectOrderStateCount()
    },
    selectOrderStateCount() {
      this.tableLoading = true
      order_state_count(this.page.query).then(resp => {
        if (resp.success) {
          this.orderStateList = resp.data
        }
      }).finally(() => {
        this.tableLoading = false
      })
    },
    // 选中事件
    handleSelectionChange(row) {
      this.selected = row
    },
    resetQueryForm() {
      this.$refs.query.resetFields()
      this.page.query.customerId = undefined
      this.$refs.customerQuery.resetQueryForm()
      this.$refs.dictSelect1.resetActive()
      this.$refs.dictSelect2.resetActive()
      this.$refs.dictSelect3.resetActive()
      this.page.query.orderState = '-1'
      this.doPage()
    },
    // 生产按钮点击
    produceClick() {
      if (this.selected.length === 0) {
        this.$message.warning('请选择需要安排生产的订单')
        return
      }
      this.$confirm('是否将选中的订单安排生产?', '排产提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableLoading = true
        const data = { ids: this.selected.map(item => item.id) }
        produce(data).then(resp => {
          if (resp.success) {
            this.$message.success('操作成功')
            this.doPage()
          }
        }).finally(() => {
          this.tableLoading = false
        })
      })
    },
    // 新增按钮点击
    saveClick() {
      this.$router.push({ path: '/sale/order/save' })
    },
    // 修改按钮点击
    updateClick(type, row) {
      if (type === 'tableBtn') {
        if (this.selected.length === 0) {
          this.$message.warning('请选择一条订单')
          return
        } else if (this.selected.length !== 1) {
          this.$message.warning('只能选择一条订单')
          return
        }
        this.updateVisible = true
        this.$nextTick(() => {
          this.$refs.updateModule.init(this.selected[0].id)
        })
      } else {
        this.updateVisible = true
        this.$nextTick(() => {
          this.$refs.updateModule.init(row.id)
        })
      }
    },
    // 取消订单
    cancelClick(type, row) {
      let data
      if (type === 'tableBtn') {
        if (this.selected.length === 0) {
          this.$message.warning('请选择一条订单')
          return
        } else if (this.selected.length !== 1) {
          this.$message.warning('只能选择一条订单')
          return
        }
        data = this.selected[0]
      } else {
        data = row
      }
      let title
      if (data.orderState === '1') {
        title = '此订单已生产，是否取消此订单'
      } else {
        title = `客户名称：${data.customerName}，数量：${data.quantity}，是否取消此订单`
      }
      this.$confirm(title, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableLoading = true
        order_cancel(data.id).then(resp => {
          if (resp.success) {
            this.$message.success('取消成功')
            this.doPage()
          }
        }).finally(() => {
          this.tableLoading = false
        })
      })
    },
    // 详情按钮点击
    infoClick(row) {
      this.$router.push({ path: '/sale/order/detail', query: { id: row.id, from: this.$route.path }})
    },
    // 批量删除
    handleBatchDelete() {
      if (this.selected.length === 0) {
        this.$message.warning('请选择一条或多条订单')
        return
      }
      this.$confirm('是否批量删除选中的订单?', '删除提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        this.tableLoading = true
        const data = { ids: this.selected.map(item => item.id) }
        order_delete(data).then(resp => {
          if (resp.success) {
            this.$message.success('删除成功')
          }
        }).finally(() => {
          this.doPage()
        })
      })
    },
    terminationClick() {
      if (this.selected.length === 0) {
        this.$message.warning('请选择一条或多条订单')
        return
      }
      this.$confirm('是否提前终止选中的订单？终止后订单状态将为已完成', '提前终止提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        this.tableLoading = true
        const data = { ids: this.selected.map(item => item.id) }
        order_termination(data).then(resp => {
          if (resp.success) {
            this.$message.success('终止成功')
          }
        }).finally(() => {
          this.doPage()
        })
      })
    },
    bomClick() {
      if (this.selected.length !== 1) {
        this.$message.warning('请选择一条订单')
        return
      }
      this.bomVisible = true
      this.$nextTick(() => {
        this.$refs.bomModule.init(this.selected[0].id)
      })
    },
    handleCloseBom() {
      this.bomVisible = false
    },
    // 分页大小
    handleSizeChange(val) {
      this.page.size = val
      this.doPage()
    },
    // 页码
    handleCurrentChange(val) {
      this.page.page = val
      this.doPage()
    },
    closeDialog(val) {
      if (val) {
        this.doPage()
      }
    },
    handleDelConfirm(row) {
      this.tableLoading = true
      const data = { ids: [row.id] }
      order_delete(data).then(resp => {
        if (resp.success) {
          this.$message.success('删除成功')
          this.doPage()
        }
      }).finally(() => {
        this.tableLoading = false
      })
    },
    handleChooseCustomer(row) {
      if (row) {
        this.page.query.customerId = row.id
      }
    },
    handleCloseUpdate() {
      this.updateVisible = false
      this.doPage()
    },
    handleCloseOs() {
      this.osVisible = false
      this.doPage()
    },
    handleTabClick(tab) {
      this.page.query.orderState = tab.name
      this.doPage()
    },
    handleDictSelectChange() {
      this.doPage()
    },
    // 外发订单
    osClick() {
      if (this.selected.length === 0) {
        this.$message.warning('请选择需要外发的订单')
        return
      }
      if (this.selected[0].orderState !== '0') {
        this.$message.warning('只能外发待处理的订单')
        return
      }
      this.osVisible = true
      this.$nextTick(() => {
        this.$refs.osOrderModule.init(null, this.selected[0].id)
      })
    }
  }
}
</script>

<style scoped>

</style>
